<template>
  <view class="set-page">
    <!-- 顶部导航 -->
    <view class="status-bar" :style="{ height: navHeight + 'px', 'padding-top': statusBarHeight + 'px' }">
      <view class="nav-bar">
        <view class="nav-bar-left">
          <image src="/static/left_arrow.png" class="nav-back-icon" @click="goBack" />
        </view>
        <view class="nav-bar-title">我的好友</view>
        <view class="nav-bar-right"></view>
      </view>
    </view>
    <view class="status-height-color" :style="{ height: navHeight + 'px', 'padding-top': statusBarHeight + 'px' }">
    </view>

    <!-- 搜索框 -->
    <!-- <view class="search-container">
      <view class="search-box">
        <image class="search-icon" src="/static/image/search.png" />
        <input class="search-input" v-model="searchKeyword" placeholder="搜索好友" confirm-type="search"
          @input="onSearchInput" />
        <image v-if="searchKeyword" class="clear-icon" src="/static/image/clear.png" @click="clearSearch" />
      </view>
    </view> -->

    <!-- 新朋友 -->
    <view class="new-friend-container" @click="onNewFriendClick">
      <view class="new-friend-icon">
        <image class="new-friend-icon-img" src="/static/new-friend.png" mode="scaleToFill" />
      </view>
      <view class="new-friend-title">新的朋友</view>
    </view>
    <!-- 好友列表 -->
    <scroll-view class="main-scroll-view" scroll-y :scroll-with-animation="true" :enhanced="true" :bounces="true"
      :show-scrollbar="false" :style="{ height: scrollViewHeight }" @scroll="onContainerScroll"
      @scrolltolower="onScrollToLower">
      <view class="friend-list-container">
        <view class="friend-list">
          <view class="friend-item" v-for="(friend, index) in filteredFriendList"
            :key="(friend.friendId || friend.id) + '-' + index" @click="onFriendClick(friend)">
            <!-- 左侧头像 -->
            <view class="friend-avatar-wrapper">
              <view class="friend-avatar"
                :style="{ backgroundImage: `url(${getAvatarUrl(friend.avatar) || '/static/default_avatar.jpg'})` }"
                :class="{ 'loaded': friend.avatarLoaded }">
              </view>
              <!-- 隐藏的image标签用于监听加载事件 -->
              <image class="hidden-avatar-image" :src="getAvatarUrl(friend.avatar) || '/static/default_avatar.jpg'"
                @load="onAvatarLoad(index)" @error="onAvatarError(index)" />
              <!-- 加载动画 -->
              <view class="avatar-loading" v-if="!friend.avatarLoaded">
                <view class="avatar-loading-spinner"></view>
              </view>
              <!-- 骨架屏占位符 -->
              <view class="avatar-skeleton" v-if="!friend.avatarLoaded">
                <view class="avatar-skeleton-shimmer"></view>
              </view>
            </view>
            <!-- 中间内容区域 -->
            <view class="friend-content">
              <view class="friend-title-row">
                <text class="friend-name">{{ friend.name || '好友名称' }}</text>
              </view>
              <!-- <text class="friend-desc">{{ friend.description || '好友简介信息...' }}</text> -->
            </view>
          </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-more" v-if="friendLoading">
          <view class="loading-spinner"></view>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 无数据状态 -->
        <view class="empty-friend" v-if="!friendLoading && filteredFriendList.length === 0">
          <image class="empty-img" src="/static/empty_state.png" />
          <text class="empty-text">暂无好友</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  name: 'MyFriend',
  data() {
    return {
      navHeight: "", //整体顶部导航栏的高度
      statusBarHeight: "", //状态栏高度
      scrollViewHeight: 0, // 滚动视图高度
      searchKeyword: "", // 搜索关键词
      friendLoading: false, // 好友加载状态
      friendList: [], // 好友列表，从接口获取
      pageInfo: {
        page: 1,
        pageSize: 20,
        hasMore: true
      }
    }
  },
  computed: {
    filteredFriendList() {
      if (!this.searchKeyword) {
        return this.friendList;
      }
      // 使用增强版搜索方法
      return this.searchFriends(this.searchKeyword);
    }
  },
  onLoad() {
    let { statusBarHeight, system } = uni.getSystemInfoSync();
    this.statusBarHeight = statusBarHeight;
    this.navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
    // 计算滚动视图高度
    this.calculateScrollViewHeight();
    // 不在onLoad中加载好友列表，避免与onShow重复调用
    // this.loadFriendList();
  },
  onShow() {
    // 加载好友列表
    this.loadFriendList(true);
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    onNewFriendClick() {
      uni.navigateTo({
        url: '/homePages/NewMyFriend'
      })
    },

    // 搜索输入
    onSearchInput(e) {
      this.searchKeyword = e.detail.value;
    },

    // 清除搜索
    clearSearch() {
      this.searchKeyword = "";
    },

    // 头像加载成功
    onAvatarLoad(index) {
      if (this.friendList[index]) {
        this.$set(this.friendList[index], 'avatarLoaded', true);
      }
    },

    // 头像加载失败
    onAvatarError(index) {
      if (this.friendList[index]) {
        // 加载失败时使用默认头像
        this.$set(this.friendList[index], 'avatar', '/static/default_avatar.jpg');
        this.$set(this.friendList[index], 'avatarLoaded', true);
      }
    },

    // 获取头像URL
    getAvatarUrl(avatar) {
      if (!avatar) {
        return '/static/default_avatar.jpg';
      }
      // 如果已经是完整url，直接返回
      if (/^https?:\/\//.test(avatar)) return avatar;
      // 防止多斜杠
      return 'https://tob.cycyai.com/' + avatar.replace(/^\/+/, '');
    },

    // 容器滚动事件
    onContainerScroll(e) {
    },

    // 滚动到底部
    onScrollToLower() {
      // 加载更多数据
      this.onLoadMore();
    },

    // 加载更多
    async onLoadMore() {
      if (this.pageInfo.hasMore && !this.friendLoading) {
        // 显式传递false参数，表示追加模式
        await this.loadFriendList(false);
      }
    },

    // 点击好友项
    onFriendClick(friend) {
      uni.navigateTo({
        url: '/homePages/groupChat?friendId=' + friend.friendId
      })
    },
    // 计算滚动视图高度
    calculateScrollViewHeight() {
      const { statusBarHeight, system } = uni.getSystemInfoSync();
      const navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
      this.scrollViewHeight = `calc(100vh - ${navHeight}px)`;
    },

    // 加载好友列表
    async loadFriendList(isRefresh = false) {
      try {
        if (isRefresh) {
          this.friendLoading = true;
          // 重置分页信息
          this.pageInfo.page = 1;
          this.pageInfo.hasMore = true;
        }
        // 获取用户信息
        let userInfo = uni.getStorageSync('userInfo');
        const userid = userInfo?.data?.userid || userInfo?.userid || '';

        if (!userid) {
          uni.showToast({
            title: '用户信息获取失败',
            icon: 'none'
          });
          return;
        }

        // 调用获取我的好友列表接口

        const response = await this.$Request.postApi('/bot/api/agentcgetmyuserfriendlist', {
          userid: userid
        });

        if (response.status === 1) {
          // 成功获取数据
          if (response.data && Array.isArray(response.data)) {
            // 处理接口返回的数据，转换为页面需要的格式
            const processedFriends = response.data.map(item => {
              const userInfo = item.showUserInfo || {};
              const avatar = userInfo.user_head || '/static/default_avatar.jpg';
              return {
                id: item.id,
                friendId: item.friendid,
                userId: item.userid,
                name: userInfo.nickname || '未知用户',
                avatar: avatar,
                avatarLoaded: avatar === '/static/default_avatar.jpg', // 默认头像直接设置为已加载
                status: item.status,
              };
            });

            if (isRefresh) {
              // 刷新时替换整个列表
              this.friendList = processedFriends;
            } else {
              // 加载更多时追加到列表
              this.friendList = [...this.friendList, ...processedFriends];
            }

            // 更新分页信息
            this.pageInfo.hasMore = processedFriends.length >= this.pageInfo.pageSize;
            if (this.pageInfo.hasMore) {
              this.pageInfo.page++;
            }


            // 延迟检查头像加载状态，确保网络头像能够正确显示
            this.$nextTick(() => {
              this.checkAvatarLoadingStatus();

            });
          } else {
            if (isRefresh) {
              this.friendList = [];
            }
            this.pageInfo.hasMore = false;
          }
        } else {
          // 获取失败
          uni.showToast({
            title: response.message || '获取好友列表失败',
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('获取好友列表失败:', error);
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      } finally {
        // 无论刷新还是加载更多，都需要结束loading状态
        this.friendLoading = false;
      }
    },



    // 获取好友统计信息
    getFriendStats() {
      return {
        total: this.friendList.length,
        online: this.friendList.filter(friend => friend.isOnline).length,
        blocked: this.friendList.filter(friend => friend.isBlocked).length,
        groups: [...new Set(this.friendList.map(friend => friend.group).filter(Boolean))]
      };
    },

    // 根据分组筛选好友
    getFriendsByGroup(groupName) {
      return this.friendList.filter(friend => friend.group === groupName);
    },

    // 搜索好友（增强版）
    searchFriends(keyword) {
      if (!keyword) return this.friendList;

      const searchTerm = keyword.toLowerCase();
      return this.friendList.filter(friend =>
        friend.name.toLowerCase().includes(searchTerm) ||
        friend.remark.toLowerCase().includes(searchTerm) ||
        friend.tags.some(tag => tag.toLowerCase().includes(searchTerm))
      );
    },



    // 检查头像加载状态
    checkAvatarLoadingStatus() {
      // 延迟检查，确保DOM更新完成
      setTimeout(() => {
        this.friendList.forEach((friend, index) => {
          if (!friend.avatarLoaded && friend.avatar !== '/static/default_avatar.jpg') {
            // 如果头像还未加载且不是默认头像，尝试重新加载
            // 强制触发头像重新加载
            this.forceRefreshAvatar(index);
          }
        });
      }, 100);
    },

    // 强制刷新头像
    forceRefreshAvatar(index) {
      if (this.friendList[index]) {
        const friend = this.friendList[index];
        if (friend.avatar && friend.avatar !== '/static/default_avatar.jpg') {
          // 添加时间戳强制重新加载
          const newAvatarUrl = friend.avatar + '?t=' + Date.now();
          this.$set(this.friendList[index], 'avatar', newAvatarUrl);
          this.$set(this.friendList[index], 'avatarLoaded', false);
        }
      }
    },

    // 批量刷新所有头像
    refreshAllAvatars() {
      this.friendList.forEach((friend, index) => {
        if (friend.avatar && friend.avatar !== '/static/default_avatar.jpg') {
          this.forceRefreshAvatar(index);
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.set-page {
  min-height: 100vh;
  background: #100D05;
  padding: 0 32rpx;
  color: #fff;
}

.status-bar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #100D05;
  display: flex;
  align-items: center;
  color: #fff;
  font-weight: 500;
  font-size: 35rpx;

  .nav-bar {
    display: flex;
    align-items: center;
    width: 100%;

    .nav-bar-left {
      display: flex;
      align-items: center;
      margin-left: 32rpx;

      .nav-back-icon {
        width: 46.15rpx;
        height: 46.15rpx;
      }
    }

    .nav-bar-title {
      flex: 1;
      text-align: center;
      font-size: 35rpx;
      font-weight: 500;
    }

    .nav-bar-right {
      width: 60rpx;
    }
  }
}

.status-height-color {
  background-color: #100D05;
}

// 搜索框
.search-container {
  // padding: 0 30rpx;
  margin-top: 20rpx;
  margin-bottom: 30rpx;

  .search-box {
    display: flex;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 40rpx;
    padding: 16rpx 30rpx;
    margin-bottom: 20rpx;

    .search-icon {
      width: 38rpx;
      height: 38rpx;
      margin-right: 20rpx;
    }

    .search-input {
      flex: 1;
      height: 48rpx;
      line-height: 48rpx;
      font-size: 28rpx;
      color: #fff;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5);
      }
    }

    .clear-icon {
      width: 29rpx;
      height: 29rpx;
      margin-left: 20rpx;
    }
  }
}

.new-friend-container {
  display: flex;
  align-items: center;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
  padding-bottom: 16rpx;
  margin-top: 20rpx;

  .new-friend-icon {
    width: 80rpx;
    height: 80rpx;
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 30rpx;

    .new-friend-icon-img {
      width: 50rpx;
      height: 50rpx;
    }
  }

  .new-friend-title {
    font-size: 30rpx;
    font-weight: 600;
  }
}

// 主滚动视图
.main-scroll-view {
  width: 100%;
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
  padding-top: 0;
  box-sizing: border-box;
}

// 好友列表容器
.friend-list-container {
  // padding: 0 30rpx;
  padding-bottom: 120rpx;
  min-height: 100%;
}

// 好友列表
.friend-list {
  -webkit-overflow-scrolling: touch;

  .friend-item {
    display: flex !important;
    align-items: center;
    padding: 20rpx 0;
    min-height: 84rpx;
    border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
    -webkit-transform: translateZ(0);
    transform: translateZ(0);

    &:last-child {
      border-bottom: none;
      margin-bottom: 40rpx;
    }

    // 头像包装器
    .friend-avatar-wrapper {
      position: relative;
      width: 84rpx;
      height: 84rpx;
      border-radius: 50%;
      margin-right: 30rpx;
      flex-shrink: 0;
      overflow: hidden;
      background-color: #2c2c2e;

      .friend-avatar {
        width: 100%;
        height: 100%;
        border-radius: 50%;
        background-size: cover;
        background-position: center;
        background-repeat: no-repeat;
        background-color: #2c2c2e;
        opacity: 1;
        transition: opacity 0.3s ease-in-out;

        &.loaded {
          opacity: 1;
        }
      }

      .hidden-avatar-image {
        position: absolute;
        top: -9999px;
        left: -9999px;
        width: 1px;
        height: 1px;
        opacity: 0;
        pointer-events: none;
      }

      // 加载动画
      .avatar-loading {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: transparent;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 1;
        transition: opacity 0.3s ease-in-out;

        .avatar-loading-spinner {
          width: 40rpx;
          height: 40rpx;
          border: 3rpx solid rgba(0, 123, 255, 0.2);
          border-top: 3rpx solid #007bff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          box-shadow: 0 0 20rpx rgba(0, 123, 255, 0.3);
        }
      }

      // 骨架屏占位符
      .avatar-skeleton {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: #2c2c2e;
        border-radius: 50%;
        animation: shimmer 1.5s infinite;
        z-index: 0;

        .avatar-skeleton-shimmer {
          width: 100%;
          height: 100%;
          background: inherit;
          border-radius: 50%;
        }
      }
    }

    // 好友内容
    .friend-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      min-width: 0;
      height: 100%;

      .friend-title-row {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin-bottom: 0;
        height: 100%;

        .friend-name {
          flex: 1;
          font-size: 32rpx;
          color: #fff;
          font-weight: 600;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          line-height: 1.2;
        }
      }
    }

  }
}

// 加载更多
.loading-more {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx 0;

  .loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 4rpx solid rgba(0, 123, 255, 0.2);
    border-top: 4rpx solid #007bff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
  }

  .loading-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.5);
  }
}

// 无数据状态
.empty-friend {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;

  .empty-img {
    width: 180rpx;
    height: 120rpx;
    margin-bottom: 40rpx;
    opacity: 0.5;
  }

  .empty-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.5);
    text-align: center;
  }
}

// 动画
@keyframes spin {
  0% {
    transform: rotate(0deg);
    opacity: 0.8;
  }

  50% {
    opacity: 1;
  }

  100% {
    transform: rotate(360deg);
    opacity: 0.8;
  }
}

@keyframes shimmer {
  0% {
    background-position: -200% 0;
  }

  100% {
    background-position: 200% 0;
  }
}

// 适配不同平台
/* #ifdef APP-PLUS */
.friend-item {
  padding: 20rpx 0;
  min-height: 84rpx;
}

.friend-avatar-wrapper {
  width: 84rpx;
  height: 84rpx;
}

.main-scroll-view {
  -webkit-overflow-scrolling: touch;
  overscroll-behavior: contain;
}

/* #endif */

/* #ifdef MP-WEIXIN */
.friend-item {
  padding: 20rpx 0;
  min-height: 84rpx;
}

.friend-avatar-wrapper {
  width: 84rpx;
  height: 84rpx;
}

/* #endif */

/* #ifdef H5 */
.friend-item {
  padding: 20rpx 0;
  min-height: 84rpx;
}

.friend-avatar-wrapper {
  width: 84rpx;
  height: 84rpx;
}

/* #endif */
</style>
